<template>
  <div style="width: 100%;font-family: PingFangSC-Regular;">
    <template>
      <div v-if="mode === 'edit'">
        <div class="content-box">
          <div :class="{'input-disabled' : disabledOrReadonly}" style="height: 100%;flex: 1;">
            <template v-if="value">
              {{ showValue }}
            </template>
            <div v-else class="placeholder">
              {{ !disabledOrReadonly ? $attrs.placeholder : ''}}
            </div>
          </div>
          <div style="float:right;">
            <van-icon v-if="value && !disabledOrReadonly" name="clear" @click.stop="clear" />
            <van-icon name="arrow" v-if="!disabledOrReadonly" @click="openSelect" />
          </div>
        </div>
        <!-- <van-area v-model="show" title="标题" :area-list="areaList" /> -->
        <van-popup
          v-model="show"
          position="bottom"
          style="border-top-right-radius: 10px; border-top-left-radius: 10px"
        >
          <div class="btn">
            <div @click="show=false">取消</div>
            <div style="color: #212121;font-weight: 500;">请选择所在地区</div>
            <div @click="confirm" class="confirm">确定</div>
          </div>
          <div v-if="!this.selectedList.length" class="local">
            <div class="m-10">当前城市<van-icon name="replay" class="ml-10" /></div>
            <div class="ml-10">
              <van-button icon="location-o" plain type="info" style="height: 36px;" @click="choose(localCity)">{{ localCity.label }}</van-button>
            </div>
            <div class="m-10">选择城市</div>
            <div style="margin-left: 3px;">
              <van-button v-for="toSelect in toSelectedList" type="default" style="height: 36px;color: #212121;" @click="choose(toSelect)">{{ toSelect.label }}</van-button>
            </div>
          </div>
          <van-steps v-else direction="vertical" :active="active" active-color="#38f" @click-step="clickStep">
            <van-step v-for="(item, index) in selectedList">
              <img slot="active-icon" src="./circle-o.svg" alt="">
              <img slot="inactive-icon" src="./circle-o.svg" alt="">
              <div @click="changeSelect(item, index)">{{ item.label }}</div>
            </van-step>
          </van-steps>
          <div style="height:1px;background: #eee;margin: 7px 0;"></div>
      
          <ul>
            <template v-for="arr in currentOptions">
              <span style="float: left;margin-top: 10px;font-size: 14px;color: #bbb;">{{arr.word}}</span>
              <li
                v-for="(label, key) in arr.obj[arr.word]"
              :class="currentSelected && currentSelected.key === key ? 'selected' : ''"
              @click="selectItem(label, key)"
            >
              <span>{{ label }}</span>
              <van-icon v-show="currentSelected && currentSelected.key === key ? 'selected' : ''" name="success" />
            </li>
            </template>
          </ul>

        </van-popup>
      </div>
      <div v-else>
        {{ value }}
      </div>
    </template>
  </div>
</template>
  
  <script>
// npm install @vant/area-data
import { areaList } from '@vant/area-data'
import { cloneDeep, sortBy } from 'lodash'
import switchWords from '../../mixins/switchWords'
export default {
  name: "regionControl",
  props:{
    value: "",
    mode: {
      type: String,
      default:'edit'
    },
  },
  data() {
    return {
      areaList,
      show: false,
      active: 0,
      // 选中的省市区
      selectedList: [],
      // 选项中被选中的
      currentSelected: null,
      localCity: {
        label: '合肥市',
        key: '340100'
      },
    };
  },
  computed: {
    toSelectedList() {
      let arr = []
      Object.keys(areaList.city_list).forEach(city => {
        if (city % 340000 < 9999) {
          arr.push({
            label: areaList.city_list[city],
            key: city
          })
        }
      })
      return arr
    },
    disabledOrReadonly(){
      return this.$attrs.readonly || this.$attrs.disabled
    },
    currentOptions() {
      const areas = cloneDeep(this.areaList)
      let val =  !this.currentSelected ? cloneDeep(areas.province_list) : this.currentSelected.type === 'province' ? cloneDeep(areas.city_list) : cloneDeep(areas.county_list)
      if (this.currentSelected) {
        Object.keys(val).forEach(i => {
          if ((this.currentSelected.type === 'province' && i - this.currentSelected.key > 1000) || (this.currentSelected.type === 'city' && i - this.currentSelected.key > 100) || ['province', 'city'].includes(this.currentSelected.type) && (i - this.currentSelected.key < 0)) {
            delete val[i]
          } else if (this.currentSelected.type === 'county') {
            const currentSelected = this.selectedList[1]
            if (i - currentSelected.key > 100 || i - currentSelected.key < 0) {
              delete val[i]
            }
          }
        })
      }
      let arr = []
      let sortObj = {}
      let sortArr = []
      Object.keys(val).forEach(i => {
        let word = switchWords(val[i]).slice(0,1)
        // 单独处理多音字
        if (i == '500000') {
          word = 'C'
        }
        if (sortObj[word]) {
          this.$set(sortObj[word], i, val[i])
        } else {
          this.$set(sortObj, word, {
            [i]: val[i]
          })
        }
      })
      Object.keys(sortObj).forEach(i => {
        sortArr.push({
          word: i,
          obj: {
            [i]: sortObj[i]
          }
        })
      })
      arr = sortBy(sortArr, (i) => i.word)
      return arr
    },
    showValue() {
      return this.selectedList.map(i =>i.label).join('/')
    }
  },
  mounted() {
  },
  methods: {
    clear() {
      this.$emit('input', '')
      this.selectedList = []
      this.currentSelected = null
    },
    openSelect() {
      this.show = true
    },
    confirm() {
      this.$emit('input', JSON.stringify(this.selectedList))
      this.show = false
    },
    clickStep(index) {
      this.active = index
    },
    selectItem(label,key) {
      this.currentSelected = {
        label,
        key,
      }
      console.log(this.currentSelected,'==this.currentSelected')
      if (Number(key) % 10000 === 0) {
        // 省
        this.$set(this.currentSelected, 'type', 'province')
        this.selectedList = [this.currentSelected]
      } else if (Number(key) % 100 === 0) {
        // 市
        this.active = 1
        this.$set(this.currentSelected, 'type', 'city')
        this.selectedList = this.selectedList.slice(0,1).concat([this.currentSelected])
      } else {
        this.active = 2
        this.$set(this.currentSelected, 'type', 'county')
        this.selectedList = this.selectedList.slice(0,2).concat([this.currentSelected])
      }
    },
    changeSelect(item, index) {
      if (index === 0) {
        this.currentSelected = null
      } else {
        this.currentSelected = this.selectedList[index -1]
      }
    },
    choose(item) {
      Object.keys(areaList.province_list).forEach(p => {
        if (item.key %p < 9999) {
          this.selectedList = [{
            label: areaList.province_list[p],
            key: p
          }, item]
          this.selectItem(item.label, item.key)
        }
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.van-cell__value {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.content-box {
  display: flex;
}
.btn {
  padding: 10px 16px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  .confirm {
    color: var(--tagBg);
  }
}
.van-popup.van-popup--bottom {
  height: 80%;
}
.van-steps.van-steps--vertical {
    height: 123px;
    margin-left: 10px;
    img {
      background: #fff;
      height: 14px;
    }
    .van-step__title {
      margin-left: 5px;
    }
    .van-step--vertical {
      padding-bottom: 15px;
    }
}
ul {
  padding-left: 20px;
  height: calc(80vh - 182px);
  overflow: auto;
  li {
    line-height: 45px;
    font-size: 15px;
    color: #212121;
    padding-left: 25px;
  }
  li.selected {
    color: var(--tagBg);
    i.van-icon.van-icon-success {
      float: right;
      margin-right: 20px;
    }
  }
}
.local {
  font-size: 14px;
  color: #999;
}
button.van-button.van-button--default.van-button--normal {
  width: 110px;
  margin: 5px 7px;
  border-color: #ddd;

}

</style>
  